//
//  OauthViewController.swift
//  DSWeibo
//
//  Created by J on 16/4/16.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController {
    
    let WB_App_Key = "3714539610"
    let WB_App_Secret = "d23d1dcd6b6ba39feddb1409ba126604"
    let WB_App_redirect_url = "http://weibo.com/u/3106243403/home?wvr=5"
    
    
    //MARK: 懒加载
    
    private lazy var webView :UIWebView = {
        let webView =   UIWebView()
        webView.delegate = self
        return webView
    }()
    
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "小码哥微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(OauthViewController.close))
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_App_redirect_url)"
        
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        
    }
    
    ///  关闭界面
    func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    

}

extension OauthViewController:UIWebViewDelegate{
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if  !request.URL!.absoluteString.hasPrefix(WB_App_redirect_url) {
            
            return true
            
        }
        let codeStr = "code="
        let rangeOfCode = request.URL!.query!.rangeOfString(codeStr)
        if  rangeOfCode  != nil{
            let code = request.URL!.query!.substringFromIndex(rangeOfCode!.endIndex)
            print(code)
            
            loadAccessToken(code)

        }else{
            
            close()
        }
        
        
        return false
        
    }
    
    private  func loadAccessToken(code:String){
        let path = "oauth2/access_token"
        let parameters = ["client_secret":WB_App_Secret,"client_id":WB_App_Key,"grant_type":"authorization_code","code":code,"redirect_uri":WB_App_redirect_url]
        
        NetWorkTools.shareNetWorkTools().POST(path, parameters: parameters, success: { (NSURLSessionDataTask, result:AnyObject?) in
            let account = UserAccount.init(dic: result!as![String:AnyObject])
            account.saveArchiver()
            
             //获取用户信息
            account.loadUserInfo({ (account, error) in
                if account != nil {
                account?.saveArchiver()
                
            NSNotificationCenter.defaultCenter() .postNotificationName(XMGSwitchRootViewControllerKey, object: true)

                }
            })
            SVProgressHUD.showInfoWithStatus("网络不给力", mastType: SVProgressHUDMaskType.Black)

            
        }) { (task:NSURLSessionDataTask?, error:NSError) in
            SVProgressHUD.showInfoWithStatus("网络不给力", mastType: SVProgressHUDMaskType.Black)

            print(error)
        }
        
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()

    }
}
